<?
require_once(dirname(__FILE__).'/../models/Countries.php');
require_once(dirname(__FILE__).'/../models/Users.php');
require_once(dirname(__FILE__).'/../models/UsersRequests.php');
require_once(dirname(__FILE__).'/../models/Files.php');
require_once(dirname(__FILE__).'/../models/Offers.php');
require_once(dirname(__FILE__).'/../models/OffersTypes.php');
require_once(dirname(__FILE__).'/../models/Orders.php');
//require_once(dirname(__FILE__).'/../models/OrdersDetails.php');
//require_once(dirname(__FILE__).'/../models/OrdersStatusesChanges.php');

class AccountController extends Main_Controller_Action {	
	public function preDispatch()
    {
        if (!$this->loggedUser) {        
                die('Unauthorized');
        } else {
           /**
			 * Translation - Loading dictionaries common and backoffice_common
			 */
			$commonLocale = Translator::loadTranslation($this->currentLang, 'common');
			$this->view->commonLocale = $commonLocale;
			
			//Database::instance()->getConn()->debug = 1;
			$filter = "WHERE users_id != ".$this->loggedUser->getId();
			$orderBy = "ORDER BY id DESC";
			$limit = 30;
			$this->view->buyerRequests = ModelMapper::instance('UsersRequests')->findFilteredPaged($filter, $orderBy, $limit, 0);
        }
    }
    
	function indexAction(){
		$this->view->countries = ModelMapper::instance('Countries')->findAll('', "ORDER BY country ASC");
		$this->view->uploadDestination = $this->config->uploads->users->origin_dir;
		$this->view->fileTypesId = $this->config->uploads->users->fileTypesId;
		
		$this->view->user =  ModelMapper::instance('Users')->find($this->loggedUser->getId());
	}
	
	function ordersAction(){
		
        //$filter = "WHERE users_id = " . $this->loggedUser->getId() . "";
        //$orderBy = "ORDER BY id DESC";
		
        //$orders = ModelMapper::instance('Orders')->findFiltered($filter, $orderBy);
        //
        //splitOrders($orders);
		
		//$this->view->orders = ModelMapper::instance('Orders')->findFiltered($filter, $orderBy);
		$this->view->orders = false;
    }
    
    function offersAction(){
    	//$filter = "WHERE users_id = " . $this->loggedUser->getId() . "";
        //$orderBy = "ORDER BY id DESC";
    	//$this->view->offers = ModelMapper::instance('Orders')->findFiltered($filter, $orderBy);
		switch ($this->_request->getParam('filter')) {
			case 'active':{
				$statusesId = $this->config->statuses->offers->active;
				$filter = "AND statuses_id = ".$statusesId;
				$orderBy = "";
				break;
			}
			case 'pending':{
				$statusesId = $this->config->statuses->offers->pending;
				$filter = "AND statuses_id = ".$statusesId;
				$orderBy = "";
				break;
			}
			case 'inactive':{
				$statusesId = $this->config->statuses->offers->inactive;
				$filter = "AND statuses_id = ".$statusesId;
				$orderBy = "";
				break;
			}
			case 'rejected':{
				$statusesId = $this->config->statuses->offers->rejected;
				$filter = "AND statuses_id = ".$statusesId;
				$orderBy = "";
				break;
			}
			case 'blocked':{
				$statusesId = $this->config->statuses->offers->blocked;
				$filter = "AND statuses_id = ".$statusesId;
				$orderBy = "";
				break;
			}
			case 'expired':{
				$statusesId = $this->config->statuses->offers->expired;
				$filter = "AND statuses_id = ".$statusesId;
				$orderBy = "";
				break;
			}
			case 'popular':{
				$statusesId = $this->config->statuses->offers->active;
				$filter = "AND statuses_id = ".$statusesId;
				$orderBy = "";
				break;
			}
			case 'rated':{
				$statusesId = $this->config->statuses->offers->active;
				$filter = "AND statuses_id = ".$statusesId;
				$orderBy = "";
				break;
			}
			default: {
				$statusesId = $this->config->statuses->offers->active;
				$filter = "AND statuses_id = ".$statusesId;
				$orderBy = "";
				break;
			}
		}
		$this->view->activeButton = $this->_request->getParam('filter');
		//Database::instance()->getConn()->debug =1;
    	$this->view->offers = $this->loggedUser->getOffers($filter, $orderBy);
    }
    
    function requestsAction(){
    	switch ($this->_request->getParam('filter')) {
			case 'active':{
				$statusesId = $this->config->statuses->offers->active;
				$filter = "AND statuses_id = ".$statusesId;
				$orderBy = "";
				break;
			}
			case 'pending':{
				$statusesId = $this->config->statuses->offers->pending;
				$filter = "AND statuses_id = ".$statusesId;
				$orderBy = "";
				break;
			}
			case 'inactive':{
				$statusesId = $this->config->statuses->offers->inactive;
				$filter = "AND statuses_id = ".$statusesId;
				$orderBy = "";
				break;
			}
			case 'rejected':{
				$statusesId = $this->config->statuses->offers->rejected;
				$filter = "AND statuses_id = ".$statusesId;
				$orderBy = "";
				break;
			}
			case 'blocked':{
				$statusesId = $this->config->statuses->offers->blocked;
				$filter = "AND statuses_id = ".$statusesId;
				$orderBy = "";
				break;
			}
			case 'expired':{
				$statusesId = $this->config->statuses->offers->expired;
				$filter = "AND statuses_id = ".$statusesId;
				$orderBy = "";
				break;
			}
			default: {
				$statusesId = $this->config->statuses->offers->active;
				$filter = "AND statuses_id = ".$statusesId;
				$orderBy = "";
				break;
			}
		}
		$this->view->activeButton = $this->_request->getParam('filter');
		//Database::instance()->getConn()->debug =1;
    	$this->view->requests = $this->loggedUser->getRequests($filter, $orderBy);
    }
    
    function favouritesAction(){
    	//$filter = "WHERE users_id = " . $this->loggedUser->getId() . "";
        //$orderBy = "ORDER BY id DESC";
    	//$this->view->requests = ModelMapper::instance('Orders')->findFiltered($filter, $orderBy);
    	//Database::instance()->getConn()->debug = 1;
		$this->view->favourites = $this->loggedUser->getFavourites();
    }
    
    function addToFavouritesAction(){
    	
    	$obj = new UsersFavourites();
    	$obj->setUsersId($this->loggedUser->getId());
    	$obj->setOffersId(intval($this->_request->getParam('offersId')));
    	
    	header('Location: /account/favourites');
    	exit();
    }
    
    function removeFromFavouritesAction(){
    	$obj = ModelMapper::instance('UsersFavourites')->find(intval($this->_request->getParam('usersFavouritesId')));
    	$obj->delete();
    	header('Location: /account/favourites');
    	exit();
    }
    
    function balanceAction(){
    	//$filter = "WHERE users_id = " . $this->loggedUser->getId() . "";
        //$orderBy = "ORDER BY id DESC";
    	//$this->view->requests = ModelMapper::instance('Orders')->findFiltered($filter, $orderBy);
		$this->view->requests = false;
    }
    
    function addOfferAction(){
    	if ($this->_request->getParam('offerTitle') != ''){
    		$this->view->title = trim(strip_tags(stripcslashes($this->_request->getParam('offerTitle'))));
    	} else {
    		$this->view->title = '';
    	}
    	
    	$this->view->countries = ModelMapper::instance('Countries')->findAll();
    	$this->view->offerTypes = ModelMapper::instance('OffersTypes')->findAll();
    	$this->view->uploadDestination = $this->config->uploads->offers->origin_dir;
		$this->view->fileTypesId = $this->config->uploads->offers->fileTypesId;
    }
    
    function saveOfferAction(){
    	//Database::instance()->getConn()->debug = 1;
		$formData = $this->_request->getParam('addForm');
		
		//debug($formData);
		if (intval($formData['offersId']) >0) {
			$obj = ModelMapper::instance('Offers')->find(intval($formData['offersId']));
			$mainImageId = $obj->getMainImageId();
		}
		else {
			$obj = new Offers(null,null,false);
			$mainImageId = NULL;
		}
		
		if (intval($formData['filesId']) != 0){
			if ($mainImageId != NULL && $mainImageId != intval($formData['filesId'][0])){
				$file = ModelMapper::instance('File')->find($mainImageId);
				$file->delete();
				/**
				 * TODO UNLINK FILE
				 */
				//unlink($mainImageId);
			}
			
			$obj->setMainImageId(intval($formData['filesId'][0]));
		} else 
			$obj->setMainImageId($mainImageId);		
		
		$formData['price'] = 5;
		$formData['requireShipping'] = isset($formData['requireShipping'])?$formData['requireShipping']:0;	
		$formData['additionaShippingPrice'] = isset($formData['requireShipping'])?$formData['additionalShippingPrice']:0;	
		$formData['countrySelected'] = isset($formData['requireShipping'])?$formData['countrySelected']:'';
		$formData['shippingPrice'] = isset($formData['requireShipping'])?$formData['shippingPrice']:0;
		
		$obj->setAppsId($this->apps['id']);
		$obj->setUsersId($this->loggedUser->getId());
		$obj->setStatusesId($this->config->statuses->offers->pending);
		$obj->setOffersTypesId($formData['offersTypesId']);
		$obj->setCategoriesId($formData['categoriesId']);
		$obj->setTitle(trim(strip_tags(stripcslashes($formData['title']))));
		$obj->setTeaser(trim(strip_tags(stripcslashes($formData['teaser']))));
		$obj->setDescription(trim(strip_tags(stripcslashes($formData['description']))));
		$obj->setInstruction(trim(strip_tags(stripcslashes($formData['instruction']))));
		$obj->setTags(trim(strip_tags(stripcslashes($formData['tags']))));
		//$obj->setAddDate();
		//$obj->setExpireDate();
		$obj->setPrice($formData['price']);
		$obj->setRequireShipping($formData['requireShipping']);
		$obj->setShippingPrice($formData['shippingPrice']);
		$obj->setRealizationDays($formData['realizationDays']);
		$obj->setCountrySelected($formData['countrySelected']);
		$obj->setAdditionaShippingPrice($formData['additionalShippingPrice']);
		ObjectWatcher::flushOperations();
		
		//debug($obj);
		if (sizeof($formData['filesId']) > 1){
			foreach ($formData['filesId'] as $k => $file){
				$fileObj = ModelMapper::instance('Files')->find($file);
				$fileObj->setObjectId($obj->getId());
			}
		}
		//$this->_helper->redirector('', 'account/offers');
		header('Location: /account/offers');
		exit();
    }
    
    function addRequestAction(){
    	
    }

    function saveRequestAction(){
    	//Database::instance()->getConn()->debug = 1;
		$formData = $this->_request->getParam('addForm');
		
		//debug($formData);
		if (intval($formData['usersRequestsId']) >0) {
			$obj = ModelMapper::instance('UserRequests')->find(intval($formData['usersRequestsId']));
		}
		else {
			$obj = new UsersRequests(null,null,false);
		}
		
		$obj->setUsersId($this->loggedUser->getId());
		$obj->setStatusesId($this->config->statuses->offers->pending);
		$obj->setCategoriesId($formData['categoriesId']);
		$obj->setAddDate(date('Y-m-d H:i:s'));
		$obj->setRequest(trim(strip_tags(stripcslashes($formData['request']))));
		//ObjectWatcher::flushOperations();
		//debug($obj);		
		//$this->_helper->redirector('account/requests', '');

		header('Location: /account/requests');
		exit();
    
    }
    
    function deleteRequestAction(){
    	$obj = ModelMapper::instance('UsersRequests')->find(intval($this->_request->getParam('usersRequestsId')));
    	$obj->delete();
    	
    	header('Location: /account/requests');
    	exit();   	
    }
    
    function inboxAction(){
    	require_once(dirname(__FILE__).'/../models/Discussions.php');
    	
    	$filter = "WHERE recipient_id = ".$this->loggedUser->getId()." OR users_id = ".$this->loggedUser->getId();
    	$orderBy = "ORDER BY cm_add_date DESC";
    	
    	$discussions = ModelMapper::instance('Discussions')->findFiltered($filter, $orderBy);
    	$this->view->discussions = $discussions;
    	$this->view->activeButton = 'all';
    	//$this->view->
    }
     ########### ACCOUNT OPERATIONS
    #########
    #########
    ##############################
    
    function changePasswordAction(){
    	$smarty = $this->view->getEngine();
		
		$tpl = $smarty->fetch('account/change-password.tpl');
		$this->getResponse()->setHeader('Content-Type', 'text/html')->appendBody($tpl);
		$this->getResponse()->sendResponse();
		exit();
    }
    
    function savePasswordAction(){
    	//Database::instance()->getConn()->debug =1;
    	$formData = $this->_request->getParam('addForm');
    	
    	if (md5(trim($formData['currentPassword'])) == $this->loggedUser->getPassword()){
    		$this->loggedUser->setPassword(md5(trim($formData['password'])));
    		$isValid = true;
    	} else {
    		$isValid = false;
    	}
    	$isValid = array('status' => $isValid);
    	echo json_encode($isValid);
    	$auth    = Zend_Auth::getInstance();
		$storage = $auth->getStorage();
		$storage->write(serialize($this->loggedUser));
    	exit();
    }
    
    function changeUsernameAction(){
    	$this->view->user =  ModelMapper::instance('Users')->find($this->loggedUser->getId());
    	$smarty = $this->view->getEngine();
		
		$tpl = $smarty->fetch('account/change-username.tpl');
		$this->getResponse()->setHeader('Content-Type', 'text/html')->appendBody($tpl);
		$this->getResponse()->sendResponse();
		exit();
    }
    
    function saveUsernameAction(){
    	//Database::instance()->getConn()->debug =1;
    	$formData = $this->_request->getParam('addForm');
    	$this->loggedUser->setUsername($formData['username']);
    	$isValid = array('username' => $formData['username']);
    	echo json_encode($isValid);
    	$auth    = Zend_Auth::getInstance();
		$storage = $auth->getStorage();
		$storage->write(serialize($this->loggedUser));
    	exit();
    }
    
    function changeEmailAction(){
    	$this->view->user =  ModelMapper::instance('Users')->find($this->loggedUser->getId());
    	$smarty = $this->view->getEngine();
		
		$tpl = $smarty->fetch('account/change-email.tpl');
		$this->getResponse()->setHeader('Content-Type', 'text/html')->appendBody($tpl);
		$this->getResponse()->sendResponse();
		exit();
    }
    
    function saveEmailAction(){
    	//Database::instance()->getConn()->debug =1;
    	$formData = $this->_request->getParam('addForm');
    	$this->loggedUser->setEmail($formData['email']);
    	$isValid = array('email' => $formData['email']);
    	echo json_encode($isValid);
    	$auth    = Zend_Auth::getInstance();
		$storage = $auth->getStorage();
		$storage->write(serialize($this->loggedUser));
    	exit();
    }
    
    function saveDetailsAction(){
    	//Database::instance()->getConn()->debug =1;
    	$formData = $this->_request->getParam('addForm');
    	   	
    	
    	$this->loggedUser->setSaddrFirstName($formData['sAddr']['firstName']);
		$this->loggedUser->setSaddrLastName($formData['sAddr']['lastName']);
		$this->loggedUser->setSaddrEmail($formData['sAddr']['email']);
		$this->loggedUser->setSaddrStreet($formData['sAddr']['street']);
		$this->loggedUser->setSaddrBuildingNo($formData['sAddr']['buildingNo']);
		$this->loggedUser->setSaddrApartmentNo($formData['sAddr']['apartmentNo']);
		$this->loggedUser->setSaddrPostcode($formData['sAddr']['postcode']);
		$this->loggedUser->setSaddrCity($formData['sAddr']['city']);
		$this->loggedUser->setSaddrCountry($formData['sAddr']['country']);
		$this->loggedUser->setBaddrCompanyName($formData['bAddr']['companyName']);
		$this->loggedUser->setBaddrFirstName($formData['bAddr']['firstName']);
		$this->loggedUser->setBaddrLastName($formData['bAddr']['lastName']);
		$this->loggedUser->setBaddrEmail($formData['bAddr']['email']);
		$this->loggedUser->setBaddrStreet($formData['bAddr']['street']);
		$this->loggedUser->setBaddrBuildingNo($formData['bAddr']['buildingNo']);
		$this->loggedUser->setBaddrApartmentNo($formData['bAddr']['apartmentNo']);
		$this->loggedUser->setBaddrPostcode($formData['bAddr']['postcode']);
		$this->loggedUser->setBaddrCity($formData['bAddr']['city']);
		$this->loggedUser->setBaddrCountry($formData['bAddr']['country']);
		//debug($this->loggedUser);
		$auth    = Zend_Auth::getInstance();
		$storage = $auth->getStorage();
		$storage->write(serialize($this->loggedUser));
    	exit();
    }
    
    function saveProfileAction(){
    	//Database::instance()->getConn()->debug =1;
    	$formData = $this->_request->getParam('addForm');
    	
    	//debug($formData);
		$mainImageId = $this->loggedUser->getMainImageId();
			
		$this->loggedUser->setFirstName(trim(strip_tags(stripcslashes($formData['firstName']))));
		$this->loggedUser->setLastName(trim(strip_tags(stripcslashes($formData['lastName']))));
		$this->loggedUser->setRemarks(trim(strip_tags(stripcslashes($formData['about']))));
		if (intval($formData['filesId']) != 0){
			if ($mainImageId != NULL && $mainImageId != intval($formData['filesId'])){
				$file = ModelMapper::instance('Files')->find($mainImageId);
				$file->delete();
				/**
				 * TODO UNLINK FILE
				 */
				//unlink($mainImageId);
			}
			
			$this->loggedUser->setMainImageId(intval($formData['filesId']));
		} else 
			$this->loggedUser->setMainImageId($mainImageId);   	
    	
    	//debug($this->loggedUser);
		$auth    = Zend_Auth::getInstance();
		$storage = $auth->getStorage();
		$storage->write(serialize($this->loggedUser));
		//exit();
		header('Location: /account');
    	exit();
    }
}


?>